﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Sunimage.Spjg.Common.SysMgr;

namespace Sunimage.Spjg.DAL.SysMgr
{
    public class RoleDa
    {
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="role"></param>
        public static void Update(Role role)
        {
            Update(role, DBHelper.GetDatabase(), null);
        }
        public static void Update(Role role, TranscationHelper trans)
        {
            Update(role, trans.DataBase, trans.Transaction);
        }
        public static void Update(Role role, Database db, DbTransaction trans)
        {
            try
            {
                if (trans == null)
                    db.ExecuteNonQuery("Usp_UpdateRole", role.Id, role.Name, role.Permissions, role.Remark);
                else
                    db.ExecuteNonQuery(trans, "Usp_UpdateRole", role.Id, role.Name, role.Remark);
            }
            catch (System.Data.SqlClient.SqlException sex)      // 只捕获SqlException，其余抛出继续传播
            {
                DBHelper.ParseSqlException(sex, false);
            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public static List<Role> GetAll()
        {
            Database db = DBHelper.GetDatabase();
            List<Role> roles = new List<Role>();
            using (IDataReader dataReader = db.ExecuteReader("Usp_GetRoleList"))
            {
                while (dataReader.Read())
                {
                    roles.Add(PopulateRole(dataReader));
                }
            }

            return roles;
        }

        //辅助方法
        public static Role PopulateRole(IDataReader dataReader)
        {
            Role role = new Role();
            role.Id = dataReader.GetInt32(0);
            role.Name = dataReader.GetString(1);
            role.Permissions = dataReader.IsDBNull(2) ? "" : dataReader.GetString(2);
            role.Remark = dataReader.IsDBNull(3) ? "" : dataReader.GetString(3);

            return role;
        }
    }
}
